import React, { PureComponent } from "react";
import { Card, Table, Popconfirm, Empty } from "antd";
// import Link from "umi/link";
import { connect } from "dva";
import { openNotificationWithIcon } from "utils/comm";
import UserAdd from "@/components/TenantUserAdd";
import styles from "./index.less";
import Catalogue from "./components/catalogue/Catalogue";
import PageLayout from "../../../components/pageconlayout/PageLayout";
import DealForm from "./components/DealForm";
import DealForm1 from "./components/DealForm1";
import AppDetail from "./components/AppDetail";
import BusinessDetail from "./components/BusinessDetail";
import TenantDetail from "./components/TenantDetail";
import TenantUserTable from "./components/TenantUserTable";

import {
  getMenuRouter,
  getPageOperate,
} from "../../../components/layouts/menuFn";

const TYPEMAP = {
  tenant: 1,
  app: 2,
  business: 3,
};

const EmptyNode = <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />;

@connect(({ appListMenu, AppBusinessManagement, loading, Public }) => ({
  appListMenu,
  AppBusinessManagement,
  loading,
  focusApp: appListMenu.focusApp,
  menuDataList: Public.menuDataList,
  resourceList: Public.resourceList,
}))
class FlowHandle extends PureComponent {
  getMenuRouter = getMenuRouter.bind(this);

  getPageOperate = getPageOperate.bind(this);

  tenantId = null;
  
  appId = null;

  busiId = null;

  pageSize = 6;

  current = 1;

  columns = [
    {
      title: "已授权用户",
      dataIndex: "userName",
      key: "userName",
    },
    {
      title: "授权者",
      dataIndex: "creatorName",
      key: "creatorName",
    },
    {
      title: "授权时间",
      dataIndex: "createTime",
      key: "createTime",
    },
    {
      title: "操作",
      key: "操作",
      render: (text, record) => {
        const authorizeCancel = this.getOprateDisable("authorizeCancel");
        if (!authorizeCancel) return "--";
        return (
          <Popconfirm
            title="确定要取消授权？"
            onConfirm={(e) => {
              e.preventDefault();
              this.handleExpandable(record);
            }}
            okText="确定"
            cancelText="取消"
          >
            <a>取消授权</a>
          </Popconfirm>
        );
      },
    },
  ];

  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
    this.state = {
      visible: false,
      userEditVisible: false,
      selectedKeys: [],
      route: [],
      tenantInfo: '-',
      busiInfo: null, // 业务详情
      userAddVisible: false,
    };
  }

  componentDidMount() {
    const {
      location: {
        query: { tenantId = "" },
      },
    } = this.props;
    // 从租户 点击应用列表按钮，跳转到应用管理页面，默认选中带过来的租户id
    this.setState({ selectedKeys: [`tenant|${tenantId}`] });
    this.tenantId = tenantId || '-';
    this.initAppListData();
  }

  componentDidUpdate(preProps) {
    const { focusApp } = this.props;
    const { focusApp: preFocusApp } = preProps;
    if (preFocusApp.id && `${preFocusApp.id || 0}` !== `${focusApp.id || 0}`) {
      // 应用切换更新页面数据
      this.initAppListData();
      this.resetPageData();
    }
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({ type: "AppBusinessManagement/clearData" });
  }

  setCurrentId = (tenantId, appId, busiId) => {
    this.tenantId = tenantId;
    this.appId = appId;
    this.busiId = busiId;
  }

  initAppListData = () => {
    const { dispatch } = this.props;
    this.appId = null;
    this.pageSize = 6;
    this.current = 1;
    dispatch({ type: "appListMenu/getAppListData" });
  };

  // 触发查询
  initData = () => {
    const { dispatch } = this.props;
    if (this.tenantId) {
      this.loadTenantInfo(this.tenantId);
    } else {
      if (!this.busiId) {
        dispatch({
          type: "AppBusinessManagement/getAppDetail",
          payload: { appId: this.appId },
        });   
      }
      dispatch({
        type: "AppBusinessManagement/getAuthorizedUsersList",
        payload: {
          appId: this.appId,
          pageNum: this.current,
          pageSize: this.pageSize,
        },
      });
    }
  };

  loadTenantInfo = (tenantId) => {
    const { dispatch } = this.props;
    dispatch({
      type: "tenantManagement/queryTenant",
      payload: { tenantId },
    }).then(({ datas }) => {
      if (datas) {
        this.setState({ tenantInfo: datas });
      }
    });
  };

  // 重置页面数据
  resetPageData = () => {
    const { dispatch } = this.props;
    this.setState({ selectedKeys: [] });
    dispatch({ type: "AppBusinessManagement/clearData" });
  };

  getOprateDisable = (type) => {
    const {
      location: { pathname = "" },
      menuDataList,
      resourceList,
    } = this.props;
    const res = this.getPageOperate(type, pathname, menuDataList, resourceList);
    return res;
  };

  /* 我的流程单选择 */
  handleTypeSelect = (selectedKeys = [], e, father = [], nomalSelectedKeys) => {
    // console.log(nomalSelectedKeys);
    const Keys = selectedKeys[0].split("|");
    const newSelectkeys = nomalSelectedKeys || selectedKeys;
    if (!(selectedKeys && selectedKeys[0].length > 0)) return;
    let busiInfo = null;
    let tenantInfo = null;
    if (e.node.props.isLeaf) {
      // 子节点
      const appId = father[0];
      // this.appId = appId;
      busiInfo = e.node.props.detail;
      this.setCurrentId(null, appId, Keys[0]);
    } else if (Keys[0] === "app") {
      const appId = Keys[Keys.length - 1];
      // this.appId = appId;
      this.setCurrentId(null, appId);
    } else {
      tenantInfo = '-'; // 先隐藏应用和租户详情
      this.setCurrentId(Keys[Keys.length - 1]);
    }
    this.initData();
    this.setState({ selectedKeys: newSelectkeys, busiInfo, tenantInfo });
  };

  editName = (id, isLeaf, value) => {
    if (value && value.length > 20) {
      return this.openNotificationWithIcon(
        "warning",
        "",
        `名称不要超过20个字符`,
      );
    }
    if (value === "" || (value.length > 0 && value.trim().length === 0)) {
      return this.openNotificationWithIcon("warning", "", `名称不能为空`);
    }
    if (id && isLeaf) {
      const { dispatch } = this.props;
      dispatch({
        type: "AppBusinessManagement/BusiUpdate",
        payload: { id, busiName: value },
      }).then((res) => {
        if (res.errCode === 0) {
          this.openNotificationWithIcon("success", "", `修改成功`);
          dispatch({ type: "appListMenu/getAppListData" });
        } else {
          const msg = res.errMsg || "修改失败";
          this.openNotificationWithIcon("error", "", msg);
        }
      });
    } else if (id) {
      const { dispatch } = this.props;
      dispatch({
        type: "AppBusinessManagement/AppEdit",
        payload: { id, appName: value },
      }).then((res) => {
        if (res.errCode === 0) {
          this.openNotificationWithIcon("success", "", `修改成功`);
          dispatch({ type: "appListMenu/getAppListData" });
        }
      });
    }
  };

  deleteAppBusiness = (id, isLeaf) => {
    if (id && isLeaf) {
      const { dispatch } = this.props;
      dispatch({
        type: "AppBusinessManagement/BusiDelete",
        payload: { busiId: id },
      }).then((res, errMsg) => {
        if (res.errCode === 0) {
          this.openNotificationWithIcon("success", "", `删除成功`);
          dispatch({ type: "appListMenu/getAppListData" });
        } else {
          this.openNotificationWithIcon("error", "", errMsg || "删除失败");
        }
      });
    } else if (id) {
      const { dispatch } = this.props;
      dispatch({
        type: "AppBusinessManagement/AppDelete",
        payload: { appId: id },
      }).then((res) => {
        if (res.errCode === 0) {
          this.openNotificationWithIcon("success", "", `删除成功`);
          dispatch({ type: "appListMenu/getAppListData" });
        }
      });
    }
  };

  // 查询父节点路径
  findIndexArray = (data, id, indexArray, level) => {
    const arr = Array.from(indexArray);
    for (let i = 0, len = data.length; i < len; i += 1) {
      arr.push(data[i].id);
      if (data[i].id === Number(id) && arr.length === level) {
        return arr;
      }

      const { apps, busi } = data[i];
      const children = apps || busi;
      if (children && children.length) {
        const result = this.findIndexArray(children, id, arr, level);
        if (result) {
          return result;
        }
      }
      arr.pop();
    }
    return false;
  };

  addAppBusiness = () => {
    const { dispatch, appListMenu } = this.props;
    const { appListMenuData = [] } = appListMenu;
    const { selectedKeys } = this.state;
    let route = [];

    if (selectedKeys[0]) {
      const Keys = selectedKeys[0].split("|");
      route = this.findIndexArray(
        appListMenuData,
        Keys[Keys.length - 1],
        [],
        TYPEMAP[Keys[0]],
      ); // 选中节点的父节点，0：租户，1：应用，2：业务
    }

    dispatch({
      type: "AppBusinessManagement/getTenantList",
      payload: { pageNum: 1, pageSize: 99 },
    });
    dispatch({
      type: "appListMenu/getAppList",
    });
    this.setState({
      visible: true,
      route,
    });
  };

  handleDealFormVisible = (visible) => {
    this.setState({ visible });
  };

  userEdit = () => {
    const { appListMenu } = this.props;
    const { appListMenuData = [] } = appListMenu;
    const { selectedKeys } = this.state;
    let route = [];

    if (selectedKeys[0]) {
      const Keys = selectedKeys[0].split("|");
      route = this.findIndexArray(
        appListMenuData,
        Keys[Keys.length - 1],
        [],
        TYPEMAP[Keys[0]],
      ); // 选中节点的父节点，0：租户，1：应用，2：业务
    }
    this.setState({
      userEditVisible: true,
      route,
    });
  };

  userAdd = () => {
    this.setState({ userAddVisible: true });
  }

  cancelUserAdd = () => {
    this.setState({ userAddVisible: false });
  }

  handleDealForm1Visible = (visible, isQuery) => {
    this.setState({ userEditVisible: visible });
    if (!isQuery) return;
    this.current = 1;
    this.initData();
  };

  tableChange = (pagination) => {
    this.pageSize = pagination.pageSize;
    this.current = pagination.current;
    this.initData();
  };

  handleExpandable = (record) => {
    const { dispatch } = this.props;
    dispatch({
      type: "AppBusinessManagement/authorizeCancel",
      payload: {
        appId: this.appId,
        userList: [
          {
            userCode: record.userCode,
            userName: record.userName,
            id: record.id,
          },
        ],
      },
    }).then(() => {
      this.initData();
    });
  };

  renderInfo() {
    const { tenantInfo, busiInfo } = this.state;
    const { AppBusinessManagement: { appInfo } = {} } = this.props;
    if (tenantInfo) {
      return {
        infoTitle: '租户详情',
        infoDetail: tenantInfo === '-' ? EmptyNode : <TenantDetail info={tenantInfo} />,
      };
    } else if (busiInfo) {
      return {
        infoTitle: '业务详情',
        infoDetail: busiInfo === '-' ? EmptyNode : <BusinessDetail info={busiInfo} />,
      };
    } else if (appInfo && appInfo.appCode) {
      return {
        infoTitle: '应用详情',
        infoDetail: <AppDetail appInfo={appInfo} />,
      };
    }
    return {
      infoTitle: '应用详情',
      infoDetail: EmptyNode,
    };
  }

  render() {
    const {
      loading,
      dispatch,
      appListMenu,
      AppBusinessManagement,
    } = this.props;
    const { visible, userEditVisible, selectedKeys, route, userAddVisible, tenantInfo, busiInfo } = this.state;
    const {
      tenantList,
      authorizedUsersList = [],
      usersTotalCount,
    } = AppBusinessManagement;

    const { appListMenuData = [], appList = [] } = appListMenu;
    const modalLoading = loading.models.AppBusinessManagement;
    const addUserLoading =
    loading.effects["tenantManagement/submitUsers"] || false
    const confirmLoading =
      loading.effects["AppBusinessManagement/addApp"] ||
      loading.effects["AppBusinessManagement/addBusi"];
    const autListLoading =
      loading.effects["AppBusinessManagement/getAuthorizedUsersList"];

    const { infoTitle, infoDetail } = this.renderInfo();

    return (
      <div className={styles.root}>
        <PageLayout
          leftContent={
            <Card
              title="应用目录"
              style={{ width: "100%", height: "100%" }}
              extra={
                this.getOprateDisable("add") ? (
                  <a href="#" onClick={this.addAppBusiness}>
                    + 新建
                  </a>
                ) : null
              }
              bodyStyle={{
                minHeight: window.innerHeight - 64 - 16 - 16 - 48 - 104,
              }}
            >
              <Catalogue
                CatalogueData={appListMenuData}
                treeNodeSelect={this.handleTypeSelect}
                editable
                editFunction={this.editName}
                deleteFunction={this.deleteAppBusiness}
                selectedKeys={selectedKeys}
                appEdit={this.getOprateDisable("appEdit")}
                appDelete={this.getOprateDisable("appDelete")}
                busiEdit={this.getOprateDisable("busiEdit")}
                busiDelete={this.getOprateDisable("busiDelete")}
                // defaultSelectedKeys={[appListMenuData.length>0?`${appListMenuData[0].id}`:""]}
              />
            </Card>
          }
          rightContent={
            <div>
              <Card
                title={infoTitle}
                style={{ width: "100%", minHeight: 165, marginBottom: 16 }}
                // bodyStyle={{ minHeight: window.innerHeight - 64 - 16 - 16 - 48 }}
              >
                { infoDetail }
              </Card>
              <Card
                title={
                  tenantInfo ? (
                    <div>
                      <span>已选用户列表</span>
                      <a
                        style={{ marginLeft: 24 }}
                        onClick={this.userAdd}
                        disabled={!this.tenantId || this.tenantId === '-'}
                      >
                        新增用户
                      </a>

                    </div>
                  ) : (
                    <div>
                      <span>授权用户</span>
                      {this.getOprateDisable("authorizeadd") && !busiInfo && (
                        <a
                          style={{ marginLeft: 24 }}
                          onClick={this.userEdit}
                          disabled={!this.appId}
                        >
                          新增授权
                        </a>
                      )}
                    </div>
                  )
                }
                style={{
                  width: "100%",
                  minHeight:
                    window.innerHeight - 64 - 16 - 16 - 16 - 165 - 104 + 66,
                }}
                bodyStyle={{
                  padding: 24,
                  minheight:
                    window.innerHeight -
                    64 -
                    16 -
                    16 -
                    48 -
                    16 -
                    165 -
                    104 +
                    66,
                }}
              >
                { tenantInfo ? 
                  ( tenantInfo === '-' ? EmptyNode : <TenantUserTable id={this.tenantId} getReload={f => { this.reloadTenantUserTable = f; }} />) 
                  : (
                    <Table
                      style={{
                        minHeight:
                          window.innerHeight -
                          64 -
                          16 -
                          16 -
                          48 -
                          16 -
                          165 -
                          104 -
                          57 -
                          24 -
                          25,
                      }}
                      columns={busiInfo ? this.columns.slice(0, 3) : this.columns}
                      rowKey="id"
                      loading={autListLoading}
                      dataSource={busiInfo === '-' ? [] : authorizedUsersList}
                      onChange={this.tableChange}
                      pagination={{
                        size: "small",
                        total: usersTotalCount,
                        showSizeChanger: true,
                        showQuickJumper: true,
                        current: this.current,
                        pageSize: this.pageSize,
                        pageSizeOptions: ["6", "10", "20", "30"],
                      }}
                    />
                  )
                }
              </Card>
            </div>
          }
        />
        {visible && (
          <DealForm
            // title={this.title}
            visible={visible}
            handleCancel={this.handleDealFormVisible}
            dispatch={dispatch}
            // data={this.record || {}}
            // disable={this.disable}
            confirmLoading={confirmLoading}
            tenantList={tenantList} // 所属租户下拉框列表
            appList={appList} // 所属应用下拉框列表
            route={route} // 选中节点的路径节点数据
          />
        )}
        {userEditVisible && (
          <DealForm1
            // title={this.title}
            visible={userEditVisible}
            handleCancel={this.handleDealForm1Visible}
            // dispatch={dispatch}
            appId={this.appId}
            // data={this.record || {}}
            // disable={this.disable}
            confirmLoading={modalLoading}
            tenantList={tenantList}
            appList={appList}
            route={route} // 选中节点的路径节点数据
          />
        )}
        {userAddVisible && (
          <UserAdd
            visible={userAddVisible}
            handleCancel={this.cancelUserAdd}
            dispatch={dispatch}
            id={this.tenantId}
            confirmLoading={addUserLoading}
            onOk={() => {
              if (this.reloadTenantUserTable) {
                this.reloadTenantUserTable();
              }
            }}
          />
        )}
      </div>
    );
  }
}

export default FlowHandle;
